package com.lungle.warmdiary.app.view.testcampaign.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.TextView;

import com.lungle.warmdiary.R;
import com.lungle.warmdiary.app.AppContext;
import com.lungle.warmdiary.app.api.remote.ApiFactory;
import com.lungle.warmdiary.app.base.BaseDetailFragment;
import com.lungle.warmdiary.app.base.BaseSubscriber;
import com.lungle.warmdiary.app.content.db.CommentDAO;
import com.lungle.warmdiary.app.content.db.DAOFactory;
import com.lungle.warmdiary.app.model.Entity;
import com.lungle.warmdiary.app.model.Result;
import com.lungle.warmdiary.app.model.event.CampaignStatueRefreshEvent;
import com.lungle.warmdiary.app.model.request.CampaignTestPost;
import com.lungle.warmdiary.app.model.response.CampaignMycomment;
import com.lungle.warmdiary.app.model.response.Image;
import com.lungle.warmdiary.app.ui.widget.AutoGridView;
import com.lungle.warmdiary.app.utils.LogUtils;
import com.lungle.warmdiary.app.view.testcampaign.CampaignDetailListTab;
import com.lungle.warmdiary.app.view.testcampaign.adapter.CampaignGridAdapter;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.iwf.photopicker.PhotoPicker;
import me.iwf.photopicker.PhotoPreview;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * Created by zhangxueyuan on 16/9/30.
 * <p>
 * 提交亲测-(首次 提交，再次提交)
 * <p>
 * 编辑亲测
 */
public class CampaignCommentFragment extends BaseDetailFragment implements GridView.OnItemClickListener {

    @Bind(R.id.campaign_level)
    RatingBar campaignLevel;
    @Bind(R.id.campaign_level_txt)
    TextView campaignLevelTxt;
    @Bind(R.id.editTextView)
    EditText editTextView;
    @Bind(R.id.num)
    TextView numTextview;

    @Bind(R.id.gv_images)
    AutoGridView gvImages;
    @Bind(R.id.campaign_join)
    Button campaignJoin;
    @Bind(R.id.auditInfo_text)
    TextView auditInfoText;
    @Bind(R.id.auditInfo)
    LinearLayout auditInfo;

    @Bind(R.id.android)
    CheckBox android;
    @Bind(R.id.ios)
    CheckBox ios;
    @Bind(R.id.android_imageView)
    ImageView androidImageView;
    @Bind(R.id.ios_imageView)
    ImageView iosImageView;


    private CommentDAO commentDAO;
    private CommentDAO.Comment commentPojo;

    public final int MAX_UPLOAD = 9;
    private List<String> mDisplayImaged = new ArrayList();
    private List<String> mNeedUploadImages = new ArrayList<>();
    private List<String> mUploadResult = new ArrayList<>();
    private List<String> mNeedReplaceImages = new ArrayList<>();


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_campaign_my_comment, container, false);
        ButterKnife.bind(this, view);
        initData();
        initView(view);
        if (commentDAO == null) {
            commentDAO = DAOFactory.getCommentDAO();
        }
        return view;
    }


    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(getActivity());
        if (!selectBack && commentDAO != null) {

            Observable.create(new Observable.OnSubscribe<CommentDAO.Comment>() {
                @Override
                public void call(Subscriber<? super CommentDAO.Comment> subscriber) {
                    commentPojo = commentDAO.find(productid);
                    subscriber.onNext(commentPojo);
                }
            })
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread()) // 指定 Subscriber 的回调发生在主线程
                    .subscribe(new Observer<CommentDAO.Comment>() {
                        @Override
                        public void onNext(CommentDAO.Comment comment) {
                            if (comment == null)
                                return;
                            campaignLevel.setRating(commentPojo.getRate());
                            editTextView.setText(commentPojo.getContent());
                            campaignLevelTxt.setText(CampaignDetailListTab.getTitleByRate((int) commentPojo.getRate()));

                            imagesParse(commentPojo.getImages());
                        }

                        @Override
                        public void onCompleted() {
                        }

                        @Override
                        public void onError(Throwable e) {

                            LogUtils.printLogE(e.getMessage());
                        }
                    });

        }
    }


    boolean commit = false;

    @Override
    public void onPause() {

        super.onPause();
        MobclickAgent.onPause(getActivity());
        if (!commit && !goShow && commentDAO != null) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    CommentDAO.Comment comment = commentDAO.find(productid);
                    if (comment == null) {
                        boolean b = commentDAO.insert(productid, (int) campaignLevel.getRating(), editTextView.getText().toString(), imagesGenerate());
                        LogUtils.printLogD("insert" + b);
                    } else {
                        boolean b = commentDAO.update(productid, (int) campaignLevel.getRating(), editTextView.getText().toString(), imagesGenerate());
                        LogUtils.printLogD("update" + b);
                    }
                }
            }).start();
            AppContext.showToastShort("已保存草稿");
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (commentDAO != null) commentDAO.close();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    public static final int CREATE = 2;
    public static final int UPDATE = 1;

    private static final int MAX_NUM = 400;//限制的最大字数　　
    private static final int MIN_NUM = 50;//限制的最大字数　　

    private int action;
    private CampaignMycomment comment;
    private String productid;
    private String campaignid;
    private String auditInfoString;
    private CampaignGridAdapter mAdapter;
    private CampaignMycomment campaignMycomment;

    private String baseContent;
    private int baseRate;

    @Override
    public void initData() {
        action = getArguments().getInt("action");
        productid = getArguments().getString("productid");
        campaignid = getArguments().getString("campaignid");
        auditInfoString = getArguments().getString("auditInfo");
        campaignMycomment = (CampaignMycomment) getArguments().getSerializable("CampaignMycomment");
        if (campaignMycomment != null) {
            productid = campaignMycomment.getProductid();
            campaignid = "" + campaignMycomment.getCampaignid();
            auditInfoString = campaignMycomment.getAuditInfo();
            baseContent = campaignMycomment.getContent();
            baseRate = campaignMycomment.getRate();
        }

    }

    @Override
    protected void sendRequestData() {
//        if (action == CREATE)
//            ApiFactory.getUserApi().getCampaignMy(productid, campaignid)
//                    .subscribeOn(Schedulers.io())
//                    .compose(this.<Result>bindToLifecycle())
//                    .observeOn(AndroidSchedulers.mainThread())
//                    .subscribe(getSubscriber());
    }


    @Override
    protected void executeOnLoadDataSuccess(Entity entity) {

//        comment = (CampaignMycomment) entity;
//        campaignLevel.setRating(comment.getRate());
//        editTextView.setText(comment.getContent());
//        auditInfo.setVisibility(View.VISIBLE);
//        auditInfoText.setText(comment.getAuditInfo());
//        if (action == UPDATE) {
//            if (comment.getImages() != null && comment.getImages().size() > 0) {
//                mDisplayImaged.addAll(comment.getImages());
//                if (mAdapter != null)
//                    mAdapter.notifyDataSetChanged();
//            }
//        }
    }

    @Override
    public void initView(View view) {
        if (action == UPDATE && !TextUtils.isEmpty(auditInfoString)) {
            auditInfo.setVisibility(View.VISIBLE);
            auditInfoText.setText(auditInfoString);
        }

        android.setChecked(true);
        ios.setChecked(false);
        campaignLevel.setRating(5);
        campaignLevelTxt.setText(CampaignDetailListTab.getTitleByRate(5));

        if (campaignMycomment != null) {
            campaignLevel.setRating(campaignMycomment.getRate());
            campaignLevelTxt.setText(CampaignDetailListTab.getTitleByRate(campaignMycomment.getRate()));
            mDisplayImaged = campaignMycomment.getImages();
            editTextView.setText(campaignMycomment.getContent());
        }


        campaignLevel.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
            @Override
            public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
                if (rating == 0)
                    campaignLevelTxt.setText("请打分");
                else
                    campaignLevelTxt.setText(CampaignDetailListTab.getTitleByRate((int) rating));

            }
        });

        mAdapter = new CampaignGridAdapter(getActivity(), mDisplayImaged);
        gvImages.setAdapter(mAdapter);
        gvImages.setOnItemClickListener(this);
        mAdapter.notifyDataSetChanged();


        editTextView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                v.getParent().requestDisallowInterceptTouchEvent(true);

                if (event.getAction() == MotionEvent.ACTION_UP) {
                    v.getParent().requestDisallowInterceptTouchEvent(false);
                }
                return false;
            }
        });


        editTextView.addTextChangedListener(new TextWatcher() {
            private CharSequence temp;


            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            public void onTextChanged(CharSequence s, int start, int before, int count) {
                temp = s;
            }

            public void afterTextChanged(Editable s) {
                int number = MAX_NUM - s.length();
                numTextview.setText(Html.fromHtml(String.format("还可以输入<font color=#F94848>%d</font>个字", number)));
            }
        });

    }

    @OnClick({R.id.campaign_join, R.id.android, R.id.ios})
    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.campaign_join:

                if (prepareSubmit()) {

                    if (prepareSubmit1()) {

                        Observable.from(mNeedUploadImages).subscribe(new Action1<String>() {
                            @Override
                            public void call(String url) {
                                uploadAndUpdate(url);
                            }
                        });
                    } else {
                        uploadAPi();
                    }
                }
                break;
            case R.id.android:
                android.setChecked(true);
                androidImageView.setImageResource(R.drawable.android_select);
                ios.setChecked(false);
                iosImageView.setImageResource(R.drawable.ios);


                break;
            case R.id.ios:
                android.setChecked(false);
                androidImageView.setImageResource(R.drawable.android);
                iosImageView.setImageResource(R.drawable.ios_select);
                ios.setChecked(true);
                break;
        }

    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        return super.onOptionsItemSelected(item);
    }


    private boolean prepareSubmit1() {
        for (String uri : mDisplayImaged) {
            if (!uri.startsWith("http")) {
                mNeedUploadImages.add(uri);
            }
        }
        return !mNeedUploadImages.isEmpty();

    }


    private boolean prepareSubmit() {

        if (campaignLevel.getRating() == 0) {
            AppContext.showToastShort("请打分");
            return false;

        } else if (editTextView.getText().length() < MIN_NUM) {
            if (editTextView.getText().length() == 0) {
                AppContext.showToastShort("未输入内容");
                return false;
            }
            AppContext.showToastShort(String.format("输入字数不得少于%d字", MIN_NUM));
            return false;

        } else if (editTextView.getText().length() > MAX_NUM) {
            AppContext.showToastShort(String.format("输入字数不得超过于%d字", MAX_NUM));
            return false;

        } else if (mDisplayImaged.size() == 0) {
            AppContext.showToastShort("未上传图片");
            return false;
        } else if (campaignMycomment != null && !TextUtils.isEmpty(baseContent) && baseContent.equals(editTextView.getText().toString()) && baseRate == (int) campaignLevel.getRating()) {
            AppContext.showToastShort("内容没有修改");
            return false;
        }

        return true;

    }

    private final int CODE_MUL_SELECT = 1;
    private final int CODE_SHOW = 2;

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//        PhotoPickerIntent intent = new PhotoPickerIntent(getActivity());
        int count = parent.getCount();
        int realCount = mAdapter.getRealCount();
        if (count != realCount) {

            if (position == count - 1) {//点击图片
                int remain = MAX_UPLOAD - count + 1;
                goShow = true;
                PhotoPicker.builder()
                        .setPhotoCount(remain)
                        .setShowCamera(false)
                        .start(getActivity(), this, CODE_MUL_SELECT);

            } else {
                goShow = true;
                PhotoPreview.builder()
                        .setPhotos((ArrayList) mDisplayImaged)
                        .setCurrentItem(position)
                        .setShowDeleteButton(true)
                        .start(getActivity(), this, CODE_SHOW);
            }

        } else {
            goShow = true;
            PhotoPreview.builder()
                    .setPhotos((ArrayList) mDisplayImaged)
                    .setCurrentItem(position)
                    .setShowDeleteButton(true)
                    .start(getActivity(), this, CODE_SHOW);

        }
    }

    boolean goShow = false;
    boolean selectBack = false;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        selectBack = true;
        goShow = false;
        if (data != null) {
            List<String> photos = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
            if (requestCode == CODE_MUL_SELECT) {
                if (photos == null && photos.isEmpty()) return;
                for (String path : photos) {
                    mDisplayImaged.add(path);
                    mNeedReplaceImages.add(path);

                }
                mAdapter.notifyDataSetChanged();
            } else if (requestCode == CODE_SHOW) {
                mDisplayImaged.clear();
                mDisplayImaged.addAll(photos);
                mAdapter.notifyDataSetChanged();
            }
        }
    }

    private String imagesGenerate() {
        if (mDisplayImaged == null || mDisplayImaged.isEmpty()) return null;
        StringBuffer stringBuffer = new StringBuffer();
        for (String path : mDisplayImaged) {
            stringBuffer.append(path).append(",");
        }
        stringBuffer.deleteCharAt(stringBuffer.length() - 1);
        return stringBuffer.toString();
    }

    private void imagesParse(String s) {
        if (TextUtils.isEmpty(s)) return;
        String[] strings = s.split(",");
        mDisplayImaged.clear();
        for (String s1 : strings) {

            if (s1.startsWith("http"))
                mDisplayImaged.add(s1);
            else {
                File f = new File(s1);
                if (f.exists()) {
                    mDisplayImaged.add(s1);
                    mNeedReplaceImages.add(s1);
                }
            }
        }
        mAdapter.notifyDataSetChanged();
    }


    private void uploadAndUpdate(String url) {
        showWaitDialog();
        File file = new File(url);
        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), requestFile);
        ApiFactory.getFileApi().upload(body).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<Result<Image>>(getActivity()) {
                    @Override
                    public void onCompleted() {

                        if (mNeedUploadImages.isEmpty()) {
                            hideWaitDialog();
                            uploadAPi();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        AppContext.showToast("上传失败");
                        hideWaitDialog();
                    }

                    @Override
                    public void onNext(Result<Image> result) {
                        mNeedUploadImages.remove(url);
                        mUploadResult.add(result.getData().getUrl());
                    }
                });
    }

    private void uploadAPi() {
        CampaignTestPost.CampaignTest campaignTest = new CampaignTestPost.CampaignTest(Integer.parseInt(campaignid), (int) campaignLevel.getRating(), editTextView.getText().toString(), merge(mDisplayImaged, mUploadResult));
        if (ios.isChecked()) {
            campaignTest.setOs(2);
        }
        CampaignTestPost campaignTestPost = new CampaignTestPost(campaignTest);


        Observable<Result> observable = null;
        if (action == 0) {
            observable = ApiFactory.getUserApi().campaignSubmit(campaignTestPost);
        } else {
            observable = ApiFactory.getUserApi().campaignUpdate(campaignTestPost);
        }
        observable.subscribeOn(Schedulers.io())
                .compose(this.<Result>bindToLifecycle())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<Result>() {
                    @Override
                    public void onCompleted() {
                        hideWaitDialog();
                        AppContext.showToastShort("提交成功");
                        EventBus.getDefault().post(new CampaignStatueRefreshEvent(0));
                        getActivity().finish();
                    }

                    @Override
                    public void onError(Throwable e) {
                        hideWaitDialog();
                        AppContext.showToast(e.getMessage());
                        commit = false;
                    }

                    @Override
                    public void onNext(Result result) {

                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                if (commentDAO != null) {
                                    commentDAO.remove(productid);
                                }
                            }
                        }).start();

                        commit = true;
                    }
                });
    }

    private List<String> merge(List<String> oldUrls, List<String> newUrls) {
        List<String> mergeList = new ArrayList<>();
        if (oldUrls != null) {
            mergeList.addAll(oldUrls);
            mergeList.removeAll(newUrls);
            mergeList.addAll(newUrls);
        } else {
            mergeList.addAll(newUrls);
        }
        mergeList.removeAll(mNeedReplaceImages);
        return mergeList;
    }

}
